const canvas = document.getElementById('canvas');
// document.body.appendChild(canvas);

canvas.style.position = 'fixed';
canvas.style.left = "0";
canvas.style.top = '0';
canvas.style.zIndex = -1;

const context = canvas.getContext('2d');

function resizeCanvas() {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;

  clearCanvas();
}

function clearCanvas() {
  context.fillStyle = '#000000';
  context.fillRect(0, 0, canvas.width, canvas.height);
}

resizeCanvas();

window.addEventListener('resize', resizeCanvas);

function mouseDownHandler(e) {
  const x = e.clientX;
  const y = e.clientY;

  createFireworks(x, y)
}
document.addEventListener('mousedown', mouseDownHandler);

const particles = [];

setInterval(() => {
  createFireworks(Math.random() * canvas.width, Math.random() * canvas.height);
}, 1000);
function createFireworks(x, y) {
  const count = 100; // 烟花个数
  const radius = 0;
  // 基础色度值
  const hue = Math.floor((Math.random() * 51) + 150);
  // 色度值幅度
  const hueVariance = 30;

  for (let i = 0; i < count; i++) {
    const angle = 360 / count * i; // 计算角度
    const radians = angle * Math.PI / 180; // 计算弧度

    const p = {};
    p.x = x;
    p.y = y;
    p.radians = radians;
    p.size = 2;

    p.speed = (Math.random() * 5) + .4;
    p.radius = p.speed;

    // 设置色度值
    p.hue = Math.floor(Math.random() * ((hue + hueVariance) - (hue - hueVariance)) + (hue - hueVariance));
    // 亮度值
    p.brightness = Math.floor(Math.random() * 31) + 50;
    // 透明度值
    p.alpha = (Math.floor(Math.random() * 61) + 40) / 100;

    particles.push(p);
  }
}

function drowFireworks() {
  clearCanvas();

  for(let i = 0; i < particles.length; i++) {
    const p = particles[i];
    const vx = Math.cos(p.radians) * p.radius;
    const vy = Math.sin(p.radians) * p.radius + 0.4;

    p.x += vx;
    p.y += vy;

    p.radius *= 1 - p.speed / 100;

    p.alpha -= 0.005;

    if (p.alpha <= 0) {
      particles.splice(i, 1);
      continue;
    }

    // 绘制
    context.beginPath();
    context.arc(p.x, p.y, p.size, 0, Math.PI * 2, false);
    context.closePath();
    context.fillStyle = `hsla(${p.hue}, 100%, ${p.brightness}%, ${p.alpha})`;
    context.fill();
  }
}

function tick() {
  context.globalCompositeOperation = 'destination-out';
  context.fillStyle = `rgba(0, 0, 0, ${10 / 100})`;
  context.fillRect(0, 0, canvas.width, canvas.height);
  context.globalCompositeOperation = 'lighter'

  drowFireworks();
  // 浏览器刷新，执行tick
  requestAnimationFrame(tick);
}

tick();